package com.css.zfzx.fwsjcj.modules.group.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.fwsjcj.cache.DivisionCache;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupEntity;
import com.css.zfzx.fwsjcj.modules.group.service.FwGroupService;
import com.css.zfzx.fwsjcj.modules.group.vo.FwGroupEntityVo;
import com.css.zfzx.fwsjcj.modules.group.vo.FwGroupUserFormCountVO;
import com.css.zfzx.fwsjcj.modules.group.vo.FwGroupVo;
import com.css.zfzx.fwsjcj.modules.group.vo.GroupVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/fw/group")
@Slf4j
public class FwGroupController {
    @Autowired
    FwGroupService fwGroupService;
    /**
     * 添加分组
     * @param
     * @return
     */
    @PostMapping("save/{type}")
    public RestResponse saveGroup(HttpServletRequest request, @PathVariable("type")String type, @RequestBody GroupVo groupVo){
        RestResponse restResponse=null;
        JSONObject jsonObject=new JSONObject();
        try {
            List<UserEntity> userEntities = groupVo.getList();
            StringBuilder groupuserId=new StringBuilder();
            StringBuilder userName = new StringBuilder();
            userEntities.forEach(userEntity -> {
                groupuserId.append(userEntity.getUserId()+",");
                userName.append(userEntity.getUserName()+",");
            });
            FwGroupEntity fwGroupEntity=groupVo.getFwGroupEntity();
            FwGroupEntityVo fwGroupEntityVo=new FwGroupEntityVo();
            if(groupuserId.length()<=0){
                return RestResponse.fail("小组成员不能为空");
            }
            fwGroupEntityVo.setGroupUserId(groupuserId.toString().substring(0,groupuserId.toString().length()-1));
            fwGroupEntityVo.setDivision(fwGroupEntity.getDivision());
            fwGroupEntityVo.setGroupLeader(fwGroupEntity.getGroupLeader());
            fwGroupEntityVo.setGroupNum(fwGroupEntity.getGroupNum());
            fwGroupEntityVo.setGroupName(fwGroupEntity.getGroupName());
            fwGroupEntityVo.setGroupLeaderId(fwGroupEntity.getGroupLeaderId());
            fwGroupEntityVo.setGroupMember(userName.toString().substring(0,userName.toString().length()-1));
            fwGroupEntityVo.setGroupType(fwGroupEntity.getGroupType());
            fwGroupService.saveGroup(request,fwGroupEntityVo,type);
            jsonObject.put("message","保存成功");
            restResponse=RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errormessage="保存失败";
            log.error(errormessage,e);
            restResponse=RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /***
     * 分页查询小组
     * @return
     */
    @GetMapping("page")
    public RestResponse getPage(HttpServletRequest request, FwGroupVo fwGroupVo, String groupType){
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try{
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize=Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            json=fwGroupService.getPage(request,fwGroupVo,curPage,pageSize,groupType);
            json.put("message", "查询成功!");
            response = RestResponse.succeed(json);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /***
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("{ids}")
    public RestResponse deletGroup(@PathVariable("ids") String ids){
        RestResponse restResponse=null;
        JSONObject jsonObject=new JSONObject();
        try {
            String[] arr= ids.split(",");
            List<String> list = Arrays.asList(arr);
            fwGroupService.deletGroup(list);
            jsonObject.put("message","删除成功");
            restResponse=RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errormessage="删除失败";
            log.error(errormessage,e);
            restResponse=RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /***
     *修改小组
     * @param groupVo
     * @return
     */
    @PostMapping("/updateGroup/{type}")
    public RestResponse updateGroup(@PathVariable("type") String type,@RequestBody GroupVo groupVo){
        RestResponse restResponse=null;
        JSONObject jsonObject=new JSONObject();
        try {
            List<UserEntity> userEntities = groupVo.getList();
            StringBuilder userId = new StringBuilder();
            StringBuilder userName = new StringBuilder();
            if (userEntities.size()>0){
                userEntities.forEach(userEntity -> {
                    userId.append(userEntity.getUserId() + ",");
                    userName.append(userEntity.getUserName() + ",");
                });
            }else {
                return RestResponse.fail("小组成员选择不能为空");
            }
            FwGroupEntity fwGroupEntity=groupVo.getFwGroupEntity();
            FwGroupEntityVo fwGroupEntityVo=new FwGroupEntityVo();
            if(!StringUtils.isEmpty(userId)){
                fwGroupEntityVo.setGroupUserId(userId.toString().substring(0,userId.toString().length()-1));
            }else {
                return RestResponse.fail("小组成员选择不能为空");
            }
            fwGroupEntityVo.setDivision(fwGroupEntity.getDivision());
            fwGroupEntityVo.setGroupLeader(fwGroupEntity.getGroupLeader());
            fwGroupEntityVo.setGroupNum(fwGroupEntity.getGroupNum());
            fwGroupEntityVo.setGroupName(fwGroupEntity.getGroupName());
            fwGroupEntityVo.setGroupLeaderId(fwGroupEntity.getGroupLeaderId());
            fwGroupEntityVo.setId(fwGroupEntity.getId());
            fwGroupEntityVo.setGroupType(type);
            fwGroupEntityVo.setGroupMember(userName.toString().substring(0,userName.toString().length()-1));
            fwGroupService.updateGroup(fwGroupEntityVo,type);
            jsonObject.put("message","修改成功");
            restResponse=RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errormessage="修改失败";
            log.error(errormessage,e);
            restResponse=RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /***
     * 查看分组信息
     * @param groupId
     * @return
     */
    @GetMapping("findById")
    public RestResponse findById(String groupId){
        RestResponse restResponse=null;
        try {
            GroupVo byId = fwGroupService.findById(groupId);
            restResponse=RestResponse.succeed(byId);
        }catch (Exception e){
            String errormessage="查看失败";
            log.error(errormessage,e);
            restResponse=RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 查询组员表单
     * @param groupId
     * @return
     */
    @GetMapping("{groupId}")
    public RestResponse findGroupUser(@PathVariable("groupId") String groupId){
        RestResponse restResponse=null;
        try {
            List<FwGroupUserFormCountVO> groupUser = fwGroupService.findGroupUser(groupId);
            restResponse=RestResponse.succeed(groupUser);
        }catch (Exception e){
            String errormessage="查询失败";
            log.error(errormessage,e);
            restResponse=RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 查询加固工程小组
     * @param request
     * @param fwGroupVo
     * @return
     */
    @GetMapping("getPage")
    public RestResponse findGroup(HttpServletRequest request,FwGroupVo fwGroupVo){
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try{
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize=Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            json=fwGroupService.getPageGroup(request,fwGroupVo,curPage,pageSize);
            json.put("message", "查询成功!");
            response = RestResponse.succeed(json);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }
}
